﻿using UnityEngine;
using System.Collections;

/// <summary>
/// play random animation when camera is idle.
/// </summary>
[AddComponentMenu("wsLibrary/Camera/Camera Idle Animation")]
public class wsCameraIdle : MonoBehaviour
{
	/// <summary>
	/// how long wait for play animation.
	/// </summary>
	public float waitSecondForIdle = 300.0f;

	/// <summary>
	/// how to back to camera.
	/// </summary>
	public enum BACK_TO_CAMERA { ATONCE, REWIND };
	/// <summary>
	/// default is atonce.
	/// </summary>
	public BACK_TO_CAMERA backToCamera = BACK_TO_CAMERA.ATONCE;
	/// <summary>
	/// rewind speed for rewind back to camera mode.
	/// </summary>
	public float rewindSpeed = 1.0f;

	/// <summary>
	/// animation list names to play.
	/// </summary>
	public string[] idleAnimationName;

	private float lastClickedTime = 0;
	private int animationIndex = 0;

	private bool isPlaying = false;

	void Start()
	{
		lastClickedTime = Time.time;
	}

	void Update()
	{
		if (Input.GetMouseButtonDown(0))
		{
			isPlaying = false;
			lastClickedTime = Time.time;
			
			if( backToCamera == BACK_TO_CAMERA.ATONCE )
				StopAnimation(GetCurrentAnimationName());
			else
				BackToAnimation(GetCurrentAnimationName(), WrapMode.Loop);
		}

		if (isPlaying == false && Time.time - this.lastClickedTime > waitSecondForIdle)
		{
			isPlaying = true;
			string aniName = GetRandomAnimationName();
			animation[aniName].speed = 1.0f;
			animation[aniName].wrapMode = WrapMode.Loop;
			animation.Play(aniName);
		}
	}

	string GetCurrentAnimationName()
	{
		return idleAnimationName[animationIndex];
	}

	string GetRandomAnimationName()
	{
		this.animationIndex = Random.Range(0, idleAnimationName.Length);
		return idleAnimationName[animationIndex];
	}

	void StopAnimation(string aniName)
	{
		animation.Stop(aniName);
		animation[aniName].time = 0.01f;
		animation[aniName].speed = -rewindSpeed;
		animation[aniName].wrapMode = WrapMode.Once;
		animation.Play(aniName);
	}

	void BackToAnimation(string aniName, WrapMode playingMode)
	{
		float aniTime = animation[aniName].time;
		float aniLength = animation[aniName].length;

		int count = 0;
		while (aniTime > aniLength)
		{
			count++;
			aniTime -= aniLength;
		}

		if (playingMode == WrapMode.Loop)
		{
			if (aniTime > aniLength / 2)
			{
				aniTime = aniLength - aniTime;
			}
		}
		else if (playingMode == WrapMode.PingPong)
		{
			if (count > 0 && count % 2 == 1)
			{
				aniTime = aniLength - aniTime;
			}
		}
		else
		{
			Debug.LogError("WrapMode for rewind (" + playingMode.ToString() + ") is not supported.");
			return;
		}

		animation[aniName].time = aniTime;

		animation[aniName].speed = -rewindSpeed;
		animation[aniName].wrapMode = WrapMode.Once;
		animation.Play(aniName);
	}
}
